<html lang="en-US">

<head>
    
<title>「连载十一」Cron定时任务 - 花落雨忧</title>

<meta property="og:title" content="「连载十一」Cron定时任务 - 花落雨忧">



    



    
    <meta property="description" content="在实际的应用项目中，定时任务的使用是很常见的。你是否有过 Golang 如何做定时任务的疑问，莫非是轮询，在本文中我们将结合我们的项目讲述 Cron。
[&amp;hellip;] 我们将使用 cron 这个包，它实现了 cron 规范解析器和任务运行器，简单来讲就是包含了定时任务所需的功能
[&amp;hellip;] Cron 表达式表示一组时间，使用 6 个空格分隔的字段
可以留意到 Golang &amp;hellip;">
    <meta property="og:description" content="在实际的应用项目中，定时任务的使用是很常见的。你是否有过 Golang 如何做定时任务的疑问，莫非是轮询，在本文中我们将结合我们的项目讲述 Cron。
[&amp;hellip;] 我们将使用 cron 这个包，它实现了 cron 规范解析器和任务运行器，简单来讲就是包含了定时任务所需的功能
[&amp;hellip;] Cron 表达式表示一组时间，使用 6 个空格分隔的字段
可以留意到 Golang &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/gin/2018-04-29-cron/">「连载十一」Cron定时任务</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/04/29</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="知识点">知识点</h2>
<ul>
<li>完成定时任务的功能</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>在实际的应用项目中，定时任务的使用是很常见的。你是否有过 Golang 如何做定时任务的疑问，莫非是轮询，在本文中我们将结合我们的项目讲述 Cron。</p>
<h2 id="介绍">介绍</h2>
<p>我们将使用 <a href="https://github.com/robfig/cron">cron</a> 这个包，它实现了 cron 规范解析器和任务运行器，简单来讲就是包含了定时任务所需的功能</p>
<h3 id="cron-表达式格式">Cron 表达式格式</h3>
<table>
<thead>
<tr>
<th>字段名</th>
<th>是否必填</th>
<th>允许的值</th>
<th>允许的特殊字符</th>
</tr>
</thead>
<tbody>
<tr>
<td>秒（Seconds）</td>
<td>Yes</td>
<td>0-59</td>
<td>* / , -</td>
</tr>
<tr>
<td>分（Minutes）</td>
<td>Yes</td>
<td>0-59</td>
<td>* / , -</td>
</tr>
<tr>
<td>时（Hours）</td>
<td>Yes</td>
<td>0-23</td>
<td>* / , -</td>
</tr>
<tr>
<td>一个月中的某天（Day of month）</td>
<td>Yes</td>
<td>1-31</td>
<td>* / , - ?</td>
</tr>
<tr>
<td>月（Month）</td>
<td>Yes</td>
<td>1-12 or JAN-DEC</td>
<td>* / , -</td>
</tr>
<tr>
<td>星期几（Day of week）</td>
<td>Yes</td>
<td>0-6 or SUN-SAT</td>
<td>* / , - ?</td>
</tr>
</tbody>
</table>
<p>Cron 表达式表示一组时间，使用 6 个空格分隔的字段</p>
<p>可以留意到 Golang 的 Cron 比 Crontab 多了一个秒级，以后遇到秒级要求的时候就省事了</p>
<h3 id="cron-特殊字符">Cron 特殊字符</h3>
<p>1、星号 ( * )</p>
<p>星号表示将匹配字段的所有值</p>
<p>2、斜线 ( / )</p>
<p>斜线用户 描述范围的增量，表现为 “N-MAX/x”，first-last/x 的形式，例如 3-59/15 表示此时的第三分钟和此后的每 15 分钟，到 59 分钟为止。即从 N 开始，使用增量直到该特定范围结束。它不会重复</p>
<p>3、逗号 ( , )</p>
<p>逗号用于分隔列表中的项目。例如，在 Day of week 使用“MON，WED，FRI”将意味着星期一，星期三和星期五</p>
<p>4、连字符 ( - )</p>
<p>连字符用于定义范围。例如，9 - 17 表示从上午 9 点到下午 5 点的每个小时</p>
<p>5、问号 ( ? )</p>
<p>不指定值，用于代替 “ * ”，类似 “ _ ” 的存在，不难理解</p>
<h3 id="预定义的-cron-时间表">预定义的 Cron 时间表</h3>
<table>
<thead>
<tr>
<th>输入</th>
<th>简述</th>
<th>相当于</th>
</tr>
</thead>
<tbody>
<tr>
<td>@yearly (or @annually)</td>
<td>1 月 1 日午夜运行一次</td>
<td>0 0 0 1 1 *</td>
</tr>
<tr>
<td>@monthly</td>
<td>每个月的午夜，每个月的第一个月运行一次</td>
<td>0 0 0 1 * *</td>
</tr>
<tr>
<td>@weekly</td>
<td>每周一次，周日午夜运行一次</td>
<td>0 0 0 * * 0</td>
</tr>
<tr>
<td>@daily (or @midnight)</td>
<td>每天午夜运行一次</td>
<td>0 0 0 * * *</td>
</tr>
<tr>
<td>@hourly</td>
<td>每小时运行一次</td>
<td>0 0 * * * *</td>
</tr>
</tbody>
</table>
<h2 id="安装">安装</h2>
<pre tabindex="0"><code>$ go get -u github.com/robfig/cron
</code></pre><h2 id="实践">实践</h2>
<p>在上一章节 <a href="https://segmentfault.com/a/1190000014393602">Gin 实践 连载十 定制 GORM Callbacks</a> 中，我们使用了 GORM 的回调实现了软删除，同时也引入了另外一个问题</p>
<p>就是我怎么硬删除，我什么时候硬删除？这个往往与业务场景有关系，大致为</p>
<ul>
<li>另外有一套硬删除接口</li>
<li>定时任务清理（或转移、backup）无效数据</li>
</ul>
<p>在这里我们选用第二种解决方案来进行实践</p>
<h3 id="编写硬删除代码">编写硬删除代码</h3>
<p>打开 models 目录下的 tag.go、article.go 文件，分别添加以下代码</p>
<p>1、tag.go</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CleanAllTag</span>() <span style="color:#66d9ef">bool</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Unscoped</span>().<span style="color:#a6e22e">Where</span>(<span style="color:#e6db74">&#34;deleted_on != ? &#34;</span>, <span style="color:#ae81ff">0</span>).<span style="color:#a6e22e">Delete</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Tag</span>{})
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>2、article.go</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CleanAllArticle</span>() <span style="color:#66d9ef">bool</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Unscoped</span>().<span style="color:#a6e22e">Where</span>(<span style="color:#e6db74">&#34;deleted_on != ? &#34;</span>, <span style="color:#ae81ff">0</span>).<span style="color:#a6e22e">Delete</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Article</span>{})
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>注意硬删除要使用 <code>Unscoped()</code>，这是 GORM 的约定</p>
<h3 id="编写-cron">编写 Cron</h3>
<p>在 项目根目录下新建 cron.go 文件，用于编写定时任务的代码，写入文件内容</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;time&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;log&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/robfig/cron&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/models&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Starting...&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">cron</span>.<span style="color:#a6e22e">New</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">AddFunc</span>(<span style="color:#e6db74">&#34;* * * * * *&#34;</span>, <span style="color:#66d9ef">func</span>() {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Run models.CleanAllTag...&#34;</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">CleanAllTag</span>()
</span></span><span style="display:flex;"><span>	})
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">AddFunc</span>(<span style="color:#e6db74">&#34;* * * * * *&#34;</span>, <span style="color:#66d9ef">func</span>() {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;Run models.CleanAllArticle...&#34;</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">CleanAllArticle</span>()
</span></span><span style="display:flex;"><span>	})
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Start</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">t1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">NewTimer</span>(<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">10</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">select</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#f92672">&lt;-</span><span style="color:#a6e22e">t1</span>.<span style="color:#a6e22e">C</span>:
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">t1</span>.<span style="color:#a6e22e">Reset</span>(<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">10</span>)
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在这段程序中，我们做了如下的事情</p>
<h4 id="cronnew">cron.New()</h4>
<p>会根据本地时间创建一个新（空白）的 Cron job runner</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">New</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">Cron</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">NewWithLocation</span>(<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Location</span>())
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// NewWithLocation returns a new Cron job runner.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewWithLocation</span>(<span style="color:#a6e22e">location</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Location</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">Cron</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Cron</span>{
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">entries</span>:  <span style="color:#66d9ef">nil</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">add</span>:      make(<span style="color:#66d9ef">chan</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Entry</span>),
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">stop</span>:     make(<span style="color:#66d9ef">chan</span> <span style="color:#66d9ef">struct</span>{}),
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">snapshot</span>: make(<span style="color:#66d9ef">chan</span> []<span style="color:#f92672">*</span><span style="color:#a6e22e">Entry</span>),
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">running</span>:  <span style="color:#66d9ef">false</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">ErrorLog</span>: <span style="color:#66d9ef">nil</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">location</span>: <span style="color:#a6e22e">location</span>,
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h4 id="caddfunc">c.AddFunc()</h4>
<p>AddFunc 会向 Cron job runner 添加一个 func ，以按给定的时间表运行</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Cron</span>) <span style="color:#a6e22e">AddJob</span>(<span style="color:#a6e22e">spec</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">cmd</span> <span style="color:#a6e22e">Job</span>) <span style="color:#66d9ef">error</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">schedule</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">Parse</span>(<span style="color:#a6e22e">spec</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Schedule</span>(<span style="color:#a6e22e">schedule</span>, <span style="color:#a6e22e">cmd</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>会首先解析时间表，如果填写有问题会直接 err，无误则将 func 添加到 Schedule 队列中等待执行</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Cron</span>) <span style="color:#a6e22e">Schedule</span>(<span style="color:#a6e22e">schedule</span> <span style="color:#a6e22e">Schedule</span>, <span style="color:#a6e22e">cmd</span> <span style="color:#a6e22e">Job</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">entry</span> <span style="color:#f92672">:=</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Entry</span>{
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">Schedule</span>: <span style="color:#a6e22e">schedule</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">Job</span>:      <span style="color:#a6e22e">cmd</span>,
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">running</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">entries</span> = append(<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">entries</span>, <span style="color:#a6e22e">entry</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">add</span> <span style="color:#f92672">&lt;-</span> <span style="color:#a6e22e">entry</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>3、c.Start()</p>
<p>在当前执行的程序中启动 Cron 调度程序。其实这里的主体是 goroutine + for + select + timer 的调度控制哦</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Cron</span>) <span style="color:#a6e22e">Run</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">running</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">running</span> = <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">run</span>()
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h4 id="timenewtimer--for--select--t1reset">time.NewTimer + for + select + t1.Reset</h4>
<p>如果你是初学者，大概会有疑问，这是干嘛用的？</p>
<p>**（1）time.NewTimer **</p>
<p>会创建一个新的定时器，持续你设定的时间 d 后发送一个 channel 消息</p>
<p><strong>（2）for + select</strong></p>
<p>阻塞 select 等待 channel</p>
<p><strong>（3）t1.Reset</strong></p>
<p>会重置定时器，让它重新开始计时</p>
<p>注：本文适用于 “t.C 已经取走，可直接使用 Reset”。</p>
<hr>
<p>总的来说，这段程序是为了阻塞主程序而编写的，希望你带着疑问来想，有没有别的办法呢？</p>
<p>有的，你直接 <code>select{}</code> 也可以完成这个需求 :)</p>
<h2 id="验证">验证</h2>
<pre tabindex="0"><code>$ go run cron.go
2018/04/29 17:03:34 [info] replacing callback `gorm:update_time_stamp` from /Users/eddycjy/go/src/github.com/EDDYCJY/go-gin-example/models/models.go:56
2018/04/29 17:03:34 [info] replacing callback `gorm:update_time_stamp` from /Users/eddycjy/go/src/github.com/EDDYCJY/go-gin-example/models/models.go:57
2018/04/29 17:03:34 [info] replacing callback `gorm:delete` from /Users/eddycjy/go/src/github.com/EDDYCJY/go-gin-example/models/models.go:58
2018/04/29 17:03:34 Starting...
2018/04/29 17:03:35 Run models.CleanAllArticle...
2018/04/29 17:03:35 Run models.CleanAllTag...
2018/04/29 17:03:36 Run models.CleanAllArticle...
2018/04/29 17:03:36 Run models.CleanAllTag...
2018/04/29 17:03:37 Run models.CleanAllTag...
2018/04/29 17:03:37 Run models.CleanAllArticle...
</code></pre><p>检查输出日志正常，模拟已软删除的数据，定时任务工作 OK</p>
<h2 id="小结">小结</h2>
<p>定时任务很常见，希望你通过本文能够熟知 Golang 怎么实现一个简单的定时任务调度管理</p>
<p>可以不依赖系统的 Crontab 设置，指不定哪一天就用上了呢</p>
<h2 id="问题">问题</h2>
<p>如果你手动修改计算机的系统时间，是会导致定时任务错乱的，所以一般不要乱来。</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 02 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-04-15-gorm-callback/">「连载十」定制 GORM Callbacks</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-26-cgo/">「番外」Golang 交叉编译</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-24-golang-docker/">「连载九」将Golang应用部署到Docker</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-18-swagger/">「连载八」为它加上Swagger</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-15-reload-http/">「连载七」优雅的重启服务</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/crawler/2018-04-28-go2018/"
                                                    rel="prev">了解一下Golang的市场行情</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/talk/2018-05-21-go-fake-useragent/">Go 的 fake-useragent 了解一下</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>